<template>
  <div>
    <div class="app-container">
      <el-form :model="chartQueryParams" ref="chartQueryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="自定义时间段" label-width="110px" prop="dateRange">
          <el-date-picker
            v-model="chart.dateRange"
            size="small"
            style="width: 240px"
            :value-format="chart.dateValueFormat"
            :type="chart.dateType"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="" prop="zxtTpye">
          <el-select style="width: 100%" v-model="chartQueryParams.zxtTpye" placeholder="请选择">
            <el-option v-for="item in dateTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleChartQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetChartQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <div>
        <v-chart :forceFit="true" :height="height" :data="chartData" :scale="scale" :padding="[20, 40, 60, 40]">
          <v-tooltip />
          <v-axis />
          <v-legend />
          <v-smooth-line
            position="coord*count"
            :color="['operation', ['#FD4A4A', '#7FC378', '#F0CC3E', '#7878C3']]"
            shape="smooth"
          />
          <v-point position="coord*count" :color="['operation', ['#FD4A4A', '#7FC378', '#F0CC3E', '#7878C3']]" shape="circle" />
        </v-chart>
      </div>
    </div>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="管理员" prop="userId">
          <el-select style="width: 100%" v-model="queryParams.userId" placeholder="请选择">
            <el-option v-for="item in accountOptions" :key="item.userId" :label="item.userName" :value="item.userId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作类型" prop="operType">
          <el-select style="width: 100%" v-model="queryParams.operType" placeholder="请选择">
            <el-option v-for="(dict, index) in typeOptions" :key="dict" :label="dict" :value="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="自定义时间段" label-width="100px" prop="params">
          <el-date-picker
            v-model="dateRange"
            size="small"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="tableList">
        <el-table-column label="时间" align="center" prop="createTime" />
        <el-table-column label="管理员" align="center" prop="createBy" />
        <el-table-column label="工号/学号" align="center" prop="studentId" />
        <el-table-column label="操作类型" align="center" prop="operType" :formatter="formatOperation" />
        <el-table-column label="操作内容" align="center" prop="operType" :formatter="formatContent" />
        <el-table-column label="详情" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-document"
              @click="handleOpenDetails(scope.row)"
              v-hasPermi="['account:statistics:details']"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 详情 对话框 -->
      <el-dialog :title="details.title" :visible.sync="details.open" width="900px" append-to-body>
        <div style="margin: -12px 16px 20px" v-loading="details.loading">
          <el-table border :data="details.tableData">
            <el-table-column align="center" prop="studentId" label="工号/学号" width="100px"></el-table-column>
            <el-table-column align="center" prop="name" label="姓名" width="130px"></el-table-column>
            <el-table-column align="center" prop="phone" label="电话" width="150px"></el-table-column>
            <el-table-column align="center" prop="card" label="身份证" width="180px"></el-table-column>
            <el-table-column prop="roles" label="角色"></el-table-column>
          </el-table>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { listStat } from './service';
import DataSet from '@antv/data-set';
import DetailsTable from './detailsTable';
import { getAccount } from '@/pages/views/account/manage/service';
import { listAllAccount } from '@/pages/views/account/service';
import { listChart } from '@/pages/views/account/statistics/service';
import dayjs from 'dayjs';

const initDateRange = () => {
  const end = new Date();
  const start = new Date();
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
  return [dayjs(start).format('YYYY-MM-DD'), dayjs(end).format('YYYY-MM-DD')];
};

const scale = [
  {
    dataKey: 'coord',
    // min: 0,
    // max: 1,
  },
];
export default {
  name: 'AuditAccount',
  components: { DetailsTable },
  data() {
    return {
      // 图表信息
      chart: {
        dateValueFormat: 'yyyy-MM-dd',
        dateRange: [],
        dateType: 'daterange',
      },
      // 图表 数据
      chartList: [],
      scale,
      height: 400,
      // select 数组
      dateTypeOptions: [
        {
          value: '1',
          label: '按日统计',
        },
        {
          value: '2',
          label: '按月统计',
        },
      ],
      // 遮罩层
      loading: true,
      typeOptions: ['新增', '删除', '修改', '登录', '修改密码'],
      accountOptions: [],
      // 选中行id
      currentRow: {},
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      tableList: [],
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        operType: null,
      },
      // 图表 重置 搜索flag
      chartResetFlag: false,
      chartQueryParams: {
        beginTime: null,
        endTime: null,
        zxtTpye: '1',
      },
      details: {
        title: '账号详情',
        open: false,
        loading: false,
        tableData: [],
      },
    };
  },
  computed: {
    chartData() {
      const dv = new DataSet.View().source(this.chartList);
      dv.transform({
        type: 'fold',
        fields: ['删除', '新增', '编辑', '登录'],
        key: 'operation',
        value: 'count',
      });
      return dv.rows;
    },
  },
  watch: {
    'chartQueryParams.zxtTpye': {
      handler(newType, oldType) {
        if (parseInt(newType) === 1) {
          // 按日
          this.chart.dateValueFormat = 'yyyy-MM-dd';
          this.chart.dateType = 'daterange';
          if (!this.chartResetFlag) {
            this.chart.dateRange = [];
            this.chartQueryParams.beginTime = null;
            this.chartQueryParams.endTime = null;
          } else {
            this.chartResetFlag = false;
          }
        } else {
          // 按月
          this.chart.dateValueFormat = 'yyyy-MM';
          this.chart.dateType = 'monthrange';
          if (this.chart.dateRange && this.chart.dateRange.length) {
            const dateRange = [
              dayjs(this.chart.dateRange[0]).format('YYYY-MM'),
              dayjs(this.chart.dateRange[1]).format('YYYY-MM'),
            ];
            this.chartQueryParams.beginTime = dateRange[0];
            this.chartQueryParams.endTime = dateRange[1];
            this.chart.dateRange = dateRange;
          }
        }
      },
      deep: true,
      immediate: false,
    },
  },
  created() {
    this.getList();
    const dateRange = initDateRange();
    this.chart.dateRange = [...dateRange];
    this.chartQueryParams.beginTime = dateRange[0];
    this.chartQueryParams.endTime = dateRange[1];
    this.$nextTick(function () {
      this.getChartList();
    });
  },
  mounted() {
    listAllAccount().then((res) => {
      if (res.code === 200) {
        this.accountOptions = res.data || [];
      }
    });
  },
  methods: {
    formatOperation(row, column, cellValue, index) {
      return this.typeOptions[cellValue] || '-';
    },
    formatContent(row, _, cellValue) {
      switch (cellValue) {
        case '0':
          return '新增' + row.userName + '用户';
        case '1':
          return '删除' + row.userName + '用户';
        case '2':
          return row.userName + '用户编辑资料';
        case '3':
          return row.userName + '登录';
        case '4':
          return row.userName + '用户修改密码';
        default:
          return '-';
      }
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      listStat(this.queryParams)
        .then((response) => {
          this.tableList = response.rows;
          this.total = response.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /* 查询 图表 数据 */
    getChartList() {
      const { dateRange } = this.chart;
      const params = {
        ...this.chartQueryParams,
        beginTime: dayjs(dateRange[0]).format('YYYY-MM-DD'),
        endTime: dayjs(dateRange[1]).format('YYYY-MM-DD'),
      };
      listChart(params).then((res) => {
        if (res.code === 200 && res.data) {
          this.chartList = res.data.map((item, index) => ({
            coord: item.coord,
            删除: item.deleteO,
            新增: item.addO,
            编辑: item.editO,
            登录: item.logO,
          }));
        }
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.dateRange && this.dateRange.length) {
        this.queryParams.params = {
          beginTime: this.dateRange[0],
          endTime: this.dateRange[1],
        };
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.dateRange = [];
      this.queryParams.params = null;
      this.handleQuery();
    },
    /** 图表 搜索按钮操作 */
    handleChartQuery() {
      const { dateRange } = this.chart;
      if (!dateRange || !dateRange.length) {
        this.$message.warning('请先选择时间段');
        return;
      }
      this.chartQueryParams.beginTime = dateRange[0];
      this.chartQueryParams.endTime = dateRange[1];
      this.getChartList();
    },
    /**  图表 重置按钮操作 */
    resetChartQuery() {
      if (this.chartQueryParams.zxtTpye === '2') {
        this.chartResetFlag = true;
      }
      this.resetForm('chartQueryForm');
      const dateRange = initDateRange();
      this.chart.dateRange = [...dateRange];
      this.handleChartQuery();
    },
    /** 查看详情操作 */
    handleOpenDetails(row) {
      this.details.tableData = [];
      this.details.loading = true;
      this.details.open = true;
      getAccount(row.userId)
        .then((res) => {
          if (res.code === 200 && res.data) {
            this.details.tableData = [
              {
                userId: res.data.userId,
                name: res.data.nickName,
                phone: res.data.phonenumber,
                idCard: res.data.card,
                roles: res.roles.map((item) => item.roleName).join('，'),
              },
            ];
          }
        })
        .finally(() => {
          this.details.loading = false;
        });
    },
  },
};
</script>
